<template>
  <div class="search">
    <div class="ml-4">
      <p class="text-l text-weight-6">{{searchTip}}</p>
      <ul class="d-flex flex-wrap jc-start">
      	<li v-for="(item,index) in searchSongsList" class="w100 mb-2" @click="getSearchSongMusic(item.id,item.name)">
          <span class="songindex text-darkgray">{{index+1}}</span>
          <span class="iconfont">&#xe616; {{item.name}}</span>
          <span> - {{item.singers}}</span>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
  import { mapMutations } from 'vuex'
  export default {
    data() {
      return {
        searchSongsList: [],
        searchTip:'请输入要搜索的内容'
      }
    },
    created() {
      this.getSearchSong()
    },
    methods: {
      ...mapMutations(['SET_MUSIC_URL','SET_MUSIC_NAME']),
      async getSearchSong() {
        if(this.$route.query.q){
          const { data: res } = await this.$http.get('/search',{ params: { keywords: this.$route.query.q } })
          if(res.result.songs){
            this.searchTip = '搜索结果'
            this.searchSongsList = res.result.songs.map(item=>{
              let singers = ''
              for(var i=0;i<item.artists.length;i++){
                singers=singers+item.artists[i].name+','
              }
              let singerstr = singers.slice(0,-1)
              return{
                id: item.id,
                name:item.name,
                singers: singerstr
              }
            })
          }else{
            this.searchTip = '暂无结果'
            this.searchSongsList = []
          }
        }
      },
      async getSearchSongMusic(id,name) {
        const {data: res} = await this.$http.get('/song/url',{ params: { id } })
        this.SET_MUSIC_URL(res.data[0].url)
        //this.$parent.url = res.data[0].url
        this.SET_MUSIC_NAME(name)
      }
    },
    watch: {
      '$route.query.q':function(newV,oldV){
        if(newV !== undefined) {
          this.getSearchSong()
        }
      },
      '$route.query.s':function(newV,oldV){
        if(newV == 1) {
          this.searchTip = '请输入要搜索的内容'
          this.searchSongsList = []
        }
      }
    }
  }
</script>

<style scoped>
  .search{
    position: absolute;
    top: 9rem;
    padding-bottom: 5rem;
  }
  .songindex{
    width: 1.5rem;
    display: inline-block;
  }
</style>
